<template>
  <view class="container" :style="appThemeStyle">
    <view class="content-wrapper">
      <scroll-view class="left" :scroll-y="true">
        <view class="search-button" @click="onSearchTenant">
          <text class="iconfont icon-search"></text>
        </view>
        <view
          :class="['tenants', { 'select' : item.id === selectTenantId }]"
          v-for="(item, index) in tenants"
          :key="index"
          @click="onSelectTenant(item)"
        >
          <view>{{ item.name }}</view>
          <view v-if="item.id === selectTenantId">
            <view class="top-radius"></view>
            <view class="bottom-radius"></view>
          </view>
        </view>
      </scroll-view>
      <view class="right">
        <view class="title">筛选</view>
        <view class="dis-flex">
          <view
            v-for="(item, index) in ['总部', '门店', '店铺']"
            :key="index"
            :class="['filter-button', {'select' : selectTab === index}]"
            @click="onSelectTab(index)"
          >{{ item }}</view>
        </view>
        <scroll-view class="scroll-wrap" :scroll-y="true">
          <!-- 总部 -->
          <view class="dis-flex flex-dir-column" v-if="selectTab === 0">
            <view class="title m-top">总部</view>
            <view
              v-if="shops?.length && shops[0].id == 0"
              @click="onSelectShop(shops[0])"
              :class="['shop', {'select' : shops[0].id === selectStoreId}]"
            >
              <view>{{ shops[0].shopName }}</view>
              <view class="iconfont selected" v-if="shops[0].id === selectStoreId">&#xe6ad;</view>
            </view>
          </view>
          <!-- 门店选择区 -->
          <view class="dis-flex flex-dir-column" v-if="selectTab === 1">
            <view class="title m-top">门店</view>
            <view class="m-b-24">
              <u-search
                placeholder="门店名称"
                @custom="onSearchCancelShops"
                @clear="onSearchCancelShops"
                action-text="取消"
                :show-action="true"
                v-model="searchShops"
                :animation="true"
                shape="square"
              />
            </view>
            <view v-for="(item, index) in shops" :key="index">
              <view
                v-if="(item.shopName?.includes(searchShops)) && item.id != 0 && item.isFullControl"
                @click="onSelectShop(item)"
                :class="['shop', {'select' : item.id === selectStoreId}]"
              >
                <view>{{ item.shopName }}</view>
                <view class="iconfont selected" v-if="item.id === selectStoreId">&#xe6ad;</view>
              </view>
            </view>
          </view>
          <!-- 店铺选择区 -->
          <view class="dis-flex flex-dir-column" v-if="selectTab === 2">
            <view class="title m-top">店铺</view>
            <view class="m-b-24">
              <u-search
                placeholder="店铺名称"
                @custom="onSearchCancelStores"
                @clear="onSearchCancelStores"
                action-text="取消"
                :show-action="true"
                v-model="searchStores"
                :animation="true"
                shape="square"
              />
            </view>
            <view v-for="(item, index) in shops" :key="index">
              <view v-if="item.id !== '0' && !isEmpty(item.storeCount)">
                <view class="store-shop" @click="onStoreByShop(index)">
                  <view>{{ item.shopName }}</view>
                  <view class="more">
                    <text>{{ item.storesShow ? '收起' : '展开' }}</text>
                    <text :class="['iconfont icon-arrow-down', { 'icon-arrow-up': item.storesShow }]"></text>
                  </view>
                </view>
                <view class="store-wrapper" v-if="item.storesShow">
                  <view
                    class="store-list"
                    v-for="(store, storesIndex) in item.stores"
                    :key="storesIndex"
                  >
                    <view
                      v-if="store.storeName?.includes(searchStores)"
                      :class="['store-item', {'select' : store.storeId === selectCounterId}]"
                      @click="onSelectStore(store)"
                    >{{ store.storeName }}</view>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>
    <!-- 底部操作按钮 -->
    <view class="footer-fixed">
      <view class="btn-wrapper">
        <u-button type="primary" shape="circle" @click="onChangeStore">确认</u-button>
      </view>
    </view>
  </view>
</template>

<script>
import store from '@/store'
import * as StoreApi from '@/api/store'
import storage from '@/utils/storage'
import { LOGIN_COUNTER, SELECT_PICKUP_ID } from "@/store/mutation-types"
import { userMenus } from '@/api/user'
import { isEmpty } from '@/utils/util'
import StoreModel from "@/common/model/Store";

export default {
  data() {
    return {
      isEmpty,
      // 选项卡按钮：0.总部，1.门店，2.店铺
      selectTab: 1,
      selectTenantId: '',
      selectStoreId: '',
      selectCounterId: '',
      searchShops: '',
      searchStores: ''
    }
  },
  computed: {
    tenants() {
      return store.getters.tenants
    },
    shops() {
      return store.getters.shops
    },
    tenant() {
      return store.getters.tenant
    },
    store() {
      return store.getters.store
    },
    counter() {
      return store.getters.counter
    }
  },
  onLoad() {
    this.getShopsData(this.tenant.id)
    this.selectTenantId = this.tenant?.id
    this.selectStoreId = this.store?.id
    uni.$on('searchTenantId', this.onSearchTenantId)
  },
  onUnload() {
    // 组件销毁时移除事件监听
    uni.$off('searchTenantId')
  },
  methods: {
    onSearchTenant() {
      this.$navTo('pages/tenant/index')
    },
    onSearchTenantId(id) {
      this.selectTenantId = id
      const tenant = this.tenants.find(val => val.id === this.selectTenantId)
      this.onSelectTenant(tenant)
    },
    onSelectTab(tab) {
      this.selectTab = tab
      this.selectStoreId = ''
      this.selectCounterId = ''
    },
    onSearchCancelShops() {
      this.searchShops = ''
    },
    onSearchCancelStores() {
      this.searchStores = ''
    },
    async onSelectTenant(item) {
      this.selectTenantId = item.id
      const { data: shops } = await StoreApi.getShopsList(item.id)
      store.commit('SET_SHOPS', shops)
      this.selectStoreId = ''
      this.selectCounterId = ''
    },
    onSelectShop(item) {
      this.selectStoreId = item.id
    },
    async onStoreByShop(index) {
      const shops = this.$u.deepClone(this.shops)
      shops[index].storesShow = !shops[index].storesShow
      if (!shops[index].stores && shops[index].storesShow) {
        const { data: stores } = await StoreApi.getStoresList(shops[index].id)
        shops[index].stores = stores
      }
      store.commit('SET_SHOPS', shops)
    },
    onSelectStore(item) {
      this.selectCounterId = item.storeId
      this.selectStoreId = item.shopId
    },
    async getShopsData(id) {
      const { data: shops } = await StoreApi.getShopsList(id)
      store.commit('SET_SHOPS', shops)
    },
    async onChangeStore() {
      if (!this.selectStoreId) {
        return this.$toast('请选择需要切换的门店')
      }
      StoreApi.changeShops(this.selectTenantId, this.selectStoreId).then(async () => {
        const tenant = this.tenants.find(val => val.id === this.selectTenantId)
        store.commit('SET_TENANT', tenant)
        const currentStore = this.shops.find(val => val.id === this.selectStoreId)
        store.commit('SET_STORE', currentStore)
        const channelList = currentStore && currentStore?.shopOnlineChannels?.map(item => {
          return {
            thirdChannelId: item.thirdChannelId,
            channelName: item.thirdChannelName
          }
        }) || []
        store.commit('SET_CHANNELS', channelList)
        if (this.selectTab === 2) {
          const counter = currentStore.stores.find(val => val.storeId === this.selectCounterId)
          store.commit('SET_COUNTER', counter)
          store.commit('SET_BUSINESS_TYPE', 2)
          storage.set(LOGIN_COUNTER, this.selectCounterId)
        } else {
          store.commit('SET_COUNTER', {})
          store.commit('SET_BUSINESS_TYPE', currentStore.id == 0 ? 0 : 1)
          storage.set(LOGIN_COUNTER, 0)
        }
        try {
          const { data: pickups } = await StoreApi.getPickupList(this.selectStoreId)
          store.commit('SET_PICKUPS', pickups)
          const selectPickupId = storage.get(this.selectStoreId + SELECT_PICKUP_ID)
          const pickup = pickups.find(item => item.pickupId === selectPickupId)
          store.commit('SET_PICKUP', pickup || {})
        } catch (e) { }
        try {
          const { data: menus } = await userMenus()
          menus && store.commit('SET_MENUS', menus)
        } catch (e) { }
        store.dispatch('UserInfo').then(() => {
          uni.navigateBack({
            delta: 1
          })
          // 相应全局事件订阅: 刷新上级页面数据
          uni.$emit('syncRefresh', true)
          if (this.$checkModule('ly_tab_message')) {
            // 切换门店，刷新IMMessage
            uni.$emit('refreshIM')
          }
          // 切换门店成功，IMSocket需要重连
          getApp().globalData.imWSInstance?.connect(false)
        })
        StoreModel.logs({
          status: 1,
          operationType: 'shop_change',
          context: `当前切换门店：${currentStore.shopName}(${currentStore.id})`
        })
      }).catch(() => { })
    }
  }
};
</script>

<style lang="scss" scoped>
.container {

  .content-wrapper {
    display: flex;
    height: calc(100vh - var(--window-top) - 102rpx - constant(safe-area-inset-bottom));
    height: calc(100vh - var(--window-top) - 102rpx - env(safe-area-inset-bottom));
  }

  .left {
    width: 160rpx;
    background: #F3F5FA;

    .search-button {
      display: flex;
      width: 128rpx;
      height: 64rpx;
      border-radius: 16rpx;
      border: 2rpx solid #ffffff;
      background: #ffffff;
      align-items: center;
      justify-content: center;
      margin: 28rpx 16rpx;

      .icon-search {
        font-size: 30rpx;
        color: #999999;
      }
    }

    .tenants {
      font-size: 24rpx;
      color: #333333;
      padding: 32rpx 16rpx;
      position: relative;

      &.select {
        color: #2D71FD;
        background: #ffffff;
      }

      .top-radius {
        position: absolute;
        width: 24rpx;
        height: 24rpx;
        top: -24rpx;
        right: 0;
        background: #ffffff;
        z-index: 1;

        &::before {
          position: absolute;
          width: 24rpx;
          height: 24rpx;
          top: 0;
          left: 0;
          background: #F3F5FA;
          border-radius: 0 0 16rpx 0;
          content: '';
        }
      }

      .bottom-radius {
        position: absolute;
        width: 24rpx;
        height: 24rpx;
        bottom: -24rpx;
        right: 0;
        background: #ffffff;
        z-index: 1;

        &::after {
          position: absolute;
          width: 24rpx;
          height: 24rpx;
          top: 0;
          left: 0;
          background: #F3F5FA;
          border-radius: 0 16rpx 0 0;
          content: '';
        }
      }
    }
  }

  .right {
    width: 590rpx;
    padding: 24rpx;
    background: #fff;
    box-sizing: border-box;

    .title {
      font-size: 26rpx;
      color: #333333;
      margin-bottom: 24rpx;
      font-weight: bold;

      &.m-top {
        margin-top: 40rpx;
      }
    }

    .scroll-wrap {
      height: calc(100% - 120rpx);
    }

    .filter-button {
      display: flex;
      width: 170rpx;
      height: 66rpx;
      border-radius: 16rpx;
      opacity: 1;
      border: 2rpx solid #F3F5FA;
      background: #F3F5FA;
      align-items: center;
      justify-content: center;
      font-size: 24rpx;
      color: #666666;
      margin-right: 16rpx;

      &.select {
        color: #2D71FD;
      }
    }

    .shop {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 24rpx;
      padding: 24rpx;
      font-size: 26rpx;
      color: #333333;
      border-radius: 16rpx;
      border: 2rpx solid #EEEEEE;
      position: relative;

      &.select {
        border-color: #2D71FD;
        font-weight: bold;
      }

      .selected {
        color: #2D71FD;
        font-size: 40rpx;
        position: absolute;
        right: 24rpx;
        top: 50%;
        transform: translateY(-50%);
      }
    }

    .store-shop {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 24rpx;
      padding: 24rpx 0;
      font-size: 26rpx;
      color: #666666;

      .more {
        display: flex;
        align-items: center;
        font-size: 24rpx;
        color: #999999;

        .iconfont {
          font-size: 30rpx;
          margin-left: 8rpx;
        }
      }
    }

    .store-wrapper {
      display: flex;
      flex-wrap: wrap;

      .store-list {
        padding: 0 10rpx;
        width: 50%;
        box-sizing: border-box;

        .store-item {
          display: flex;
          justify-content: center;
          margin-bottom: 24rpx;
          padding: 24rpx;
          font-size: 26rpx;
          color: #333333;
          border-radius: 16rpx;
          border: 2rpx solid #F8F8F8;
          background: #F8F8F8;
          line-height: 40rpx;

          &.select {
            border: 2rpx solid #F0F7FF;
            background: #F0F7FF;
            color: #2D71FD;
          }
        }
      }
    }
  }
}

// 底部操作栏
.footer-fixed {
  position: fixed;
  bottom: var(--window-bottom);
  left: 0;
  right: 0;
  z-index: 11;
  // 设置ios刘海屏底部横线安全区域
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
  background: #ffffff;

  .btn-wrapper {
    padding: 16rpx 32rpx;
  }
}

/* 隐藏滚动条 */
::-webkit-scrollbar {
  width: 0;
  height: 0;
  color: transparent;
}

scroll-view ::-webkit-scrollbar {
  width: 0;
  height: 0;
  background-color: transparent;
}

</style>
